package com.neudu.glsb.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.neudu.glsb.commons.JSONReturn;
import com.neudu.glsb.dto.EmployeeAttendanceVO;
import com.neudu.glsb.pojo.EmployeeLeave;
import com.neudu.glsb.pojo.Employees;
import com.neudu.glsb.service.EmployeeLeaveService;
import com.neudu.glsb.service.EmployeesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class EmployeeLeaveController {


    @Autowired
    private EmployeeLeaveService employeeLeaveService;

    @Autowired
    private EmployeesService employeesService;

    @Autowired
    private JSONReturn jsonReturn;

    // 获取所有请假申请（修复排序问题：待审批→已通过→未通过）
//    @PostMapping("getAllLeaves")
//    public String getAllLeaves(@RequestBody Map<String, Object> pageInfoMap) {
//        try {
//            Integer pageNum = (Integer) pageInfoMap.get("pageNum");
//            Integer pageSize = (Integer) pageInfoMap.get("pageSize");
//            String status = (String) pageInfoMap.get("status");
//            String employeeName = (String) pageInfoMap.get("employeeName");
//
//            PageHelper.startPage(pageNum, pageSize);
//
//            LambdaQueryWrapper<EmployeeLeave> queryWrapper = new LambdaQueryWrapper<>();
//            if (!ObjectUtils.isEmpty(status)) {
//                if ("已审批".equals(status)) {
//                    queryWrapper.in(EmployeeLeave::getStatus, Arrays.asList("已通过", "未通过"));
//                } else {
//                    queryWrapper.eq(EmployeeLeave::getStatus, status);
//                }
//            }
//            if (!ObjectUtils.isEmpty(employeeName)) {
//                queryWrapper.like(EmployeeLeave::getEmployeeName, employeeName);
//            }
//
//            // 核心修复：使用原生SQL实现自定义排序优先级
//            // 待审批(1) → 已通过(2) → 未通过(3)，按升序排列
//            queryWrapper.last("ORDER BY " +
//                    "CASE " +
//                    "WHEN status = '待审批' THEN 1 " +
//                    "WHEN status = '已通过' THEN 2 " +
//                    "WHEN status = '未通过' THEN 3 " +
//                    "ELSE 4 " +  // 其他状态放最后
//                    "END ASC, id DESC");
//
//            List<EmployeeLeave> list = employeeLeaveService.list(queryWrapper);
//            PageInfo<EmployeeLeave> pageInfoReturn = new PageInfo<>(list);
//            return jsonReturn.returnSuccess(pageInfoReturn);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return jsonReturn.returnError(e.getMessage());
//        }
//    }
    @PostMapping("getAllLeaves")
    public String getAllLeaves(@RequestBody Map<String, Object> pageInfoMap) {
        try {
            Integer pageNum = (Integer) pageInfoMap.get("pageNum");
            Integer pageSize = (Integer) pageInfoMap.get("pageSize");
            String status = (String) pageInfoMap.get("status");
            String employeeName = (String) pageInfoMap.get("employeeName");

            PageHelper.startPage(pageNum, pageSize);

            LambdaQueryWrapper<EmployeeLeave> queryWrapper = new LambdaQueryWrapper<>();
            // 1. 状态筛选逻辑不变
            if (!ObjectUtils.isEmpty(status)) {
                if ("已审批".equals(status)) {
                    queryWrapper.in(EmployeeLeave::getStatus, Arrays.asList("已通过", "未通过"));
                } else {
                    queryWrapper.eq(EmployeeLeave::getStatus, status);
                }
            }
            // 用apply写原生SQL关联查询员工姓名（e是employees表别名）
            if (!ObjectUtils.isEmpty(employeeName)) {
                queryWrapper.apply("EXISTS (SELECT 1 FROM employees e WHERE e.id = employee_leave.employee_id AND e.employee_name LIKE CONCAT('%', {0}, '%'))", employeeName);
            }
            // 3. 修复：排序语句加表别名employee_leave，避免多表查询冲突
            queryWrapper.last("ORDER BY " +
                    "CASE " +
                    "WHEN employee_leave.status = '待审批' THEN 1 " +
                    "WHEN employee_leave.status = '已通过' THEN 2 " +
                    "WHEN employee_leave.status = '未通过' THEN 3 " +
                    "ELSE 4 " +
                    "END ASC, employee_leave.id DESC");

            List<EmployeeLeave> list = employeeLeaveService.list(queryWrapper);
            PageInfo<EmployeeLeave> pageInfoReturn = new PageInfo<>(list);
            return jsonReturn.returnSuccess(pageInfoReturn);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }
    // 根据员工姓名模糊查询请假申请
    @PostMapping("searchByName")
    public String searchByName(@RequestBody Map<String, Object> pageInfoMap) {
        try {
            Integer pageNum = (Integer) pageInfoMap.get("pageNum");
            Integer pageSize = (Integer) pageInfoMap.get("pageSize");
            String employeeName = (String) pageInfoMap.get("employeeName");

            PageHelper.startPage(pageNum, pageSize);

            // 搜索时也应用相同的排序规则
            LambdaQueryWrapper<EmployeeLeave> queryWrapper = new LambdaQueryWrapper<>();
            if (!ObjectUtils.isEmpty(employeeName)) {
                queryWrapper.like(EmployeeLeave::getEmployeeName, employeeName);
            }
            // 同样添加自定义排序
            queryWrapper.last("ORDER BY " +
                    "CASE " +
                    "WHEN status = '待审批' THEN 1 " +
                    "WHEN status = '已通过' THEN 2 " +
                    "WHEN status = '未通过' THEN 3 " +
                    "ELSE 4 " +
                    "END ASC, id DESC");

            List<EmployeeLeave> list = employeeLeaveService.list(queryWrapper);
            PageInfo<EmployeeLeave> pageInfoReturn = new PageInfo<>(list);
            return jsonReturn.returnSuccess(pageInfoReturn);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    @PostMapping("getLeaveById")
    public String getLeaveById(@RequestBody Map<String, Integer> idMap) {
        try {
            Integer id = idMap.get("id");
            if (ObjectUtils.isEmpty(id)) {
                return jsonReturn.returnError("ID不能为空");
            }
            EmployeeLeave leave = employeeLeaveService.getLeaveByIdWithEmployeeName(id);
            if (leave == null) {
                return jsonReturn.returnError("请假申请不存在");
            }
            return jsonReturn.returnSuccess(leave);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    // 审批请假申请
    @PostMapping("approveLeave")
    public String approveLeave(@RequestBody Map<String, Object> leaveMap) {
        try {
            Integer id = (Integer) leaveMap.get("id");
            String decision = (String) leaveMap.get("decision");
            if (ObjectUtils.isEmpty(id) || ObjectUtils.isEmpty(decision)) {
                return jsonReturn.returnError("ID和审批决定不能为空");
            }
            EmployeeLeave leave = employeeLeaveService.getById(id);
            if (leave != null) {
                // 确保状态值与排序逻辑中的值一致
                if ("通过".equals(decision)) {
                    leave.setStatus("已通过");
                } else if ("未通过".equals(decision)) {
                    leave.setStatus("未通过");
                }
                boolean success = employeeLeaveService.updateById(leave);
                if (success) {
                    return jsonReturn.returnSuccess();
                } else {
                    return jsonReturn.returnError("审批失败，未找到对应的请假申请信息");
                }
            } else {
                return jsonReturn.returnError("请假申请不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    // 根据员工 ID 获取员工姓名
    @GetMapping("/getEmployeeInfo")
    public String getEmployeeInfo(@RequestParam Integer id) {
        try {
            Employees employee = employeesService.getById(id);
            if (employee != null) {
                return jsonReturn.returnSuccess(Map.of("name", employee.getEmployeeName(), "phone", employee.getPhone()));
            } else {
                return jsonReturn.returnError("未找到对应的员工信息");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    // 添加请假申请
    @PostMapping("/addOneLeave")
    public String addOneLeave(@RequestBody EmployeeLeave leave) {
        try {
            leave.setStatus("待审批"); // 新增请假默认为待审批状态
            boolean save = employeeLeaveService.save(leave);
            if (save) {
                return jsonReturn.returnSuccess("请假申请提交成功");
            } else {
                return jsonReturn.returnError("请假申请提交失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }


    /**
     * 全量考勤分页接口（供前端统计模块调用）
     */

}
